package com.example.studyroom.controller;

/*
    用户功能控制类
*/

import com.example.studyroom.Entity.Reservation;
import com.example.studyroom.Entity.StudyRoom;
import com.example.studyroom.Entity.User;
import com.example.studyroom.dto.StudyRoom.StudyRoomDTO;
import com.example.studyroom.dto.User.UserInfoDTO;
import com.example.studyroom.dto.User.UserLoginDTO;
import com.example.studyroom.dto.User.UserRegisterDTO;
import com.example.studyroom.dto.User.UserReserveDTO;
import com.example.studyroom.service.ReservationService;
import com.example.studyroom.service.StudyRoomService;
import com.example.studyroom.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService; // 注入UserService依赖

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 用户登录
     *
     * @param loginDTO 包含用户名和密码
     * @return 登录成功或失败的响应
     */
    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody UserLoginDTO loginDTO) {
        User existingUser = userService.findByUserLogin(loginDTO.getUname(), loginDTO.getUpass());
        if (existingUser != null) {
            return ResponseEntity.ok("登录成功!");
        } else {
            return ResponseEntity.badRequest().body("登录失败");
        }
    }
//    @PostMapping("/login")
//    public ResponseEntity<String> login(@RequestBody UserLoginDTO loginDTO) {
//        User existingUser = userService.findByUserLogin(loginDTO.getUname(), loginDTO.getUpass());
//        System.out.println(existingUser);
//        if (existingUser != null) {
//            //生成token令牌
//            String token = UUID.randomUUID() + "";
//            //存到redis数据库
//            redisTemplate.opsForValue().set(token,existingUser, Duration.ofMillis(30L));
//            return ResponseEntity.ok("登录成功!");
//        } else {
//            return ResponseEntity.badRequest().body("登录失败");
//        }
//    }


    /**
     * 用户注册
     *
     * @param registerDTO 包含注册信息
     * @return 注册成功或失败的响应
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody UserRegisterDTO registerDTO) {
        if (userService.usernameExists(registerDTO.getUname())) {
            // 如果用户名已存在，则返回状态码409和相应的消息
            return ResponseEntity.status(HttpStatus.CONFLICT).body("该用户已存在");
        }
        User user = new User()
                .setUname(registerDTO.getUname())
                .setUpass(registerDTO.getUpass())
                .setPhone(registerDTO.getPhone())
                .setGender(registerDTO.getGender())
                .setAge(registerDTO.getAge())
                .setHobby(registerDTO.getHobby())
                .setAddress(registerDTO.getAddress());
        userService.registerUser(user);
        return ResponseEntity.ok().build();
    }

    /**
     * 获取用户信息
     *
     * @param Uname 用户名
     * @return 用户信息列表
     */
    @GetMapping("/info")
    public ResponseEntity<List<UserInfoDTO>> getUserInfo(@RequestParam String Uname) {
        List<UserInfoDTO> userInfoDTOS = userService.getUserInfo(Uname);
        return ResponseEntity.ok(userInfoDTOS);
    }

    /**
     * 修改用户信息
     *
     * @param Uname 用户名
     * @param user  包含新的用户信息
     */
    /**
     * 修改用户信息
     *
     * @param Uname 用户名
     * @param user  包含新的用户信息
     */
    @PutMapping("/modifyUserInfo/{Uname}")
    public ResponseEntity<Void> modifyUserInfo(@PathVariable String Uname, @RequestBody User user) {
        User existingUser = userService.findByUserLogin(Uname, user.getUpass()); // 根据用户名查询用户
        if (existingUser == null) {
            return ResponseEntity.notFound().build();
        }

        // 更新用户信息
        existingUser.setPhone(user.getPhone());
        existingUser.setGender(user.getGender());
        existingUser.setAge(user.getAge());
        existingUser.setHobby(user.getHobby());
        existingUser.setAddress(user.getAddress());

        userService.modifyUserInfo(existingUser); // 调用Service层方法更新用户信息

        return ResponseEntity.ok().build();
    }


    @Autowired
    private StudyRoomService studyRoomService; // 注入StudyRoomService依赖

    /**
     * 获取所有自习室信息
     *
     * @return 自习室信息列表
     */
    @GetMapping("/allstudyroom")
    public List<StudyRoomDTO> getAllStudyRooms() {
        List<StudyRoom> studyRooms = studyRoomService.getAllStudyRooms(); // 从数据库获取原始数据
        List<StudyRoomDTO> studyRoomDTOs = new ArrayList<>();
        for (StudyRoom studyRoom : studyRooms) {
            StudyRoomDTO studyRoomDTO = new StudyRoomDTO();
            studyRoomDTO.setId(studyRoom.getId());
            studyRoomDTO.setRoomName(studyRoom.getRoomName());
            studyRoomDTO.setCapacity(studyRoom.getCapacity());
            studyRoomDTO.setFacilities(studyRoom.getFacilities());
            studyRoomDTO.setAdminName(studyRoom.getAdminName());

            studyRoomDTOs.add(studyRoomDTO);
        }
        return studyRoomDTOs;
    }

    @Autowired
    private ReservationService reservationService; // 注入ReservationService依赖

    /**
     * 预约自习室
     *
     * @param userReserveDTO 包含预约信息
     * @return 预约成功的响应
     */
    @PostMapping("/reserve")
    public ResponseEntity<Void> UserReserve(@RequestBody UserReserveDTO userReserveDTO) {
        System.out.println("Received UserReserveDTO: " + userReserveDTO);
        Reservation reservation = new Reservation()
                .setUname(userReserveDTO.getName())
                .setRoomName(userReserveDTO.getRoomName())
                .setStartTime(userReserveDTO.getStartTime())
                .setEndTime(userReserveDTO.getEndTime())
                .setReserveStatus(userReserveDTO.getReserveStatus());
        reservationService.UserReserve(reservation);
        return ResponseEntity.ok().build();
    }

    /**
     * 更新剩余座位
     * 预约自习室成功之后自习室的剩余座位-1
     *
     * @param roomName 自习室名称
     * @return 更新成功或失败的响应
     */
    @PutMapping("/updatecapacity/{roomName}")
    public ResponseEntity<Void> updateCapacity(@PathVariable String roomName) {
        StudyRoom studyRoom = studyRoomService.findByRoomName(roomName);
        if (studyRoom != null && studyRoom.getCapacity() > 0) { // 检查剩余座位数是否大于0
            studyRoom.setCapacity(studyRoom.getCapacity() - 1);
            studyRoomService.updateCapacity(studyRoom);
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build(); // 座位数不足，返回错误状态码
        }
    }

    /**
     * 获取用户的所有预约
     *
     * @param Uname 用户名
     * @return 用户预约列表
     */
    @GetMapping("/myreservation")
    public ResponseEntity<List<UserReserveDTO>> getReservationByUser(@RequestParam String Uname) {
        List<UserReserveDTO> userReserveDTOS = reservationService.getReservationByUser(Uname);
        return ResponseEntity.ok(userReserveDTOS);
    }

    /**
     * 用户取消预约
     *
     * @param id 预约ID
     * @return 取消预约成功的响应
     */
    @PutMapping("/cancelReservation/{id}")
    public ResponseEntity<Void> cancelReservation(@PathVariable Integer id) {
        reservationService.cancelReservation(id); // 根据ID查找预约信息并修改状态为已取消
        return ResponseEntity.ok().build();
    }

    /**
     * 更新剩余座位
     * 用户取消预约之后剩余座位+1
     *
     * @param roomName 自习室名称
     * @return 更新成功的响应
     */
    @PutMapping("/cancelcapacity/{roomName}")
    public ResponseEntity<Void> cancelCapacity(@PathVariable String roomName) {
        StudyRoom studyRoom = studyRoomService.findByRoomName(roomName);
        studyRoom.setCapacity(studyRoom.getCapacity() + 1); // 将剩余座位加 1
        studyRoomService.updateCapacity(studyRoom);
        return ResponseEntity.ok().build();
    }
}
